import { message, Modal } from 'antd';
import type { ExportParams } from '@/types/global';
import { formatData } from './util';
import { request } from 'umi';

/**
 * @description: 导出文件
 * @param {ExportParams} exportParams 导出参数
 */
export function exportExcel(exportParams: ExportParams): Promise<void> {
  const { params, url, onFail, onSuccess, fileInfo } = exportParams;
  message.loading('导出文件中');
  return request(url, {
    method: 'POST',
    body: formatData(params),
    transformRequest: [
      res => {
        let result = '';
        Object.keys(res).forEach(key => {
          if (!Object.is(res[key], undefined) && !Object.is(res[key], null)) {
            result += `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}&`;
          }
        });
        return result;
      },
    ],
    responseType: 'blob',
  })
    .then((r: BlobPart) => {
      const blob = new Blob([r]);
      const { fileName = Date.now(), fileExtra } = fileInfo;
      const exportName = fileName + fileExtra;
      if ('download' in document.createElement('a')) {
        downloadWithAnchor(blob, exportName);
        if (typeof onSuccess === 'function') {
          onSuccess();
        }
      } else {
        throw Error('导出失败');
      }
    })
    .catch(r => {
      if (typeof onFail === 'function') {
        onFail();
      }
      message.error(r);
    });
}

/**
 * @desc: 通过a标签下载
 * @param {Blob} blob
 * @param {string} downloadTitle 下载的文件名
 * @return {void}
 */
export function downloadWithAnchor(blob: Blob, downloadTitle: string) {
  const elink = document.createElement('a');
  elink.download = downloadTitle;
  elink.style.display = 'none';
  elink.href = URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href);
  document.body.removeChild(elink);
}

/**
 * @description: base64转文件
 * @param {*} dataurl base64
 */
export function dataURLtoBlob(dataurl) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
